﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;

namespace Devonline.Identity;

/// <summary>
/// 默认的基于策略的授权控制机制
/// </summary>
public class AuthorizationHandler(ILogger<AuthorizationHandler> logger, AuthorizationService authorizationService) : AuthorizationHandler<AuthorizationRequirement>, IAuthorizationHandler
{
    private readonly ILogger<AuthorizationHandler> _logger = logger;
    private readonly AuthorizationService _authorizationService = authorizationService;

    /// <summary>
    /// 校验用户身份和授权
    /// </summary>
    /// <param name="context"></param>
    /// <param name="requirement"></param>
    /// <returns></returns>
    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, AuthorizationRequirement requirement)
    {
        if (context.HasSucceeded)
        {
            context.Succeed(requirement);
            return;
        }

        _logger.LogInformation("用户授权验证开始!");
        if ((context.User.Identity?.IsAuthenticated ?? false) && await _authorizationService.AuthorizeAsync())
        {
            _logger.LogInformation("用户已获得授权!");
            context.Succeed(requirement);
        }

        await Task.CompletedTask;
    }
}